package cn.liuweiwei.controller;


import cn.liuweiwei.domain.Message;
import cn.liuweiwei.service.MessageService;
import cn.liuweiwei.util.Result;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("messages")
@CrossOrigin
public class MessageController {

    @Autowired
    private MessageService messageService;

    /**
     * 分页查询留言记录
     *
     * @param page  当前页
     * @param limit 每页条数
     * @return 留言记录列表
     */
    @GetMapping
    public Result findAllMessage(String page, String limit) {
        PageInfo<Message> pageInfo = messageService.findAllMessage(page, limit);
        return Result.successWithCodeAndObj(pageInfo);
    }

    /**
     * 添加一条留言
     *
     * @param message
     * @return
     */
    @PostMapping
    public Result insertOneMessage(@RequestBody Message message) {
        List<Message> byEmail = messageService.findOneMessageByEmail(message.getEmail());
        if (byEmail.size() <= 0) {
            return Result.error("抱歉，你未注册，请先注册");
        }
        messageService.insertOneMessage(message);
        return Result.success("留言发布成功");
    }

    /**
     * 通过留言的id数组 删除留言
     *
     * @param ids 是一个数组
     * @return
     */
    @DeleteMapping
    public Result deleteMessage(String[] ids) {
        try {
            messageService.deleteMessageByIds(ids);
            return Result.success("删除留言成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除留言失败");
        }
    }

}
